package com.cennavi.minemapdemo.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;

import com.cennavi.minemapdemo.R;

import java.util.List;


public class IndoorAdapter extends RecyclerView.Adapter<IndoorAdapter.ViewHolder> {
    private LayoutInflater layoutInflater;
    private List<String> indoorNameList;
    private String checkedName = "";
    private ISelectListener listener;

    public IndoorAdapter(Context context, List<String> indoorNameList) {
        this.indoorNameList = indoorNameList;
        layoutInflater = LayoutInflater.from(context);
    }

    public void setListener(ISelectListener listener) {
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.indoor_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final String indoorName = indoorNameList.get(position);

        if (indoorName != null) {
            holder.text.setText(indoorName);
        }
        if (indoorName.equals(checkedName)) {
            holder.text.setChecked(true);
        } else {
            holder.text.setChecked(false);
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onSelect(indoorName);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return indoorNameList.size();
    }

    public void update(List<String> indoorNameList, String checkedName) {
        this.indoorNameList = indoorNameList;
        this.checkedName = checkedName;
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        View itemView;
        CheckedTextView text;

        public ViewHolder(View itemView) {
            super(itemView);
            this.itemView = itemView;
            text = itemView.findViewById(R.id.ctv_name);
        }
    }

    public interface ISelectListener {
        void onSelect(String indoorName);
    }
}
